package com.java110.mall.chain.supplier.adaper.jxhh;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.mall.chain.supplier.ISupplierAdapter;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.area.AreaDto;
import com.java110.dto.chain.ChainSupplierProductDto;
import com.java110.dto.chain.ChainInoutOrderProductDto;
import com.java110.dto.chain.ChainProductDto;
import com.java110.dto.chain.ChainProductValueDto;
import com.java110.dto.chain.ChainSupplierDto;
import com.java110.dto.chain.ChainSupplierCatalogDto;
import com.java110.dto.file.FileDto;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.housekeeping.HousekeepingServDto;
import com.java110.dto.product.ProductCategoryDto;
import com.java110.dto.product.ProductDto;
import com.java110.dto.product.ProductPriceRuleDto;
import com.java110.dto.product.ProductSpecValueDto;
import com.java110.dto.shop.ShopHouseDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderAddressDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.intf.cart.IStoreOrderAddressInnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartInnerServiceSMO;
import com.java110.intf.chain.IChainInoutOrderProductV1InnerServiceSMO;
import com.java110.intf.chain.IChainSupplierCatalogV1InnerServiceSMO;
import com.java110.intf.user.IAreaInnerServiceSMO;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.intf.goods.*;
import com.java110.intf.shop.IShopHouseInnerServiceSMO;
import com.java110.po.file.FileRelPo;
import com.java110.po.product.ProductCategoryPo;
import com.java110.po.product.ProductPo;
import com.java110.po.product.ProductSpecDetailPo;
import com.java110.po.product.ProductSpecPo;
import com.java110.po.product.ProductDetailPo;
import com.java110.po.product.ProductServKeywordPo;
import com.java110.po.product.ProductSpecValuePo;
import com.java110.po.shop.ShopHousePo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.utils.util.Assert;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import com.jxhh.ApiClient;
import com.jxhh.ApiResponse;
import com.jxhh.exception.ApiRequestException;
import com.jxhh.exception.MustParamsException;
import com.jxhh.goods.*;
import com.jxhh.order.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 罗之供应商对接适配器
 * 一般提供供应商 对接自己的系统
 */
@Component
public class JxhhSupplierAdapter implements ISupplierAdapter {

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderAddressInnerServiceSMO storeOrderAddressInnerServiceSMOImpl;

    @Autowired
    private IAreaInnerServiceSMO areaInnerServiceSMO;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IChainSupplierCatalogV1InnerServiceSMO chainSupplierCatalogV1InnerServiceSMO;

    @Autowired
    private IProductCategoryInnerServiceSMO productCategoryInnerServiceSMOImpl;

    @Autowired
    private IShopHouseInnerServiceSMO shopHouseInnerServiceSMOImpl;

    @Autowired
    private IProductSpecInnerServiceSMO productSpecInnerServiceSMOImpl;

    @Autowired
    private IProductSpecDetailInnerServiceSMO productSpecDetailInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductDetailInnerServiceSMO productDetailInnerServiceSMOImpl;

    @Autowired
    private IProductServKeywordInnerServiceSMO productServKeywordInnerServiceSMOImpl;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IProductPriceRuleV1InnerServiceSMO productPriceRuleV1InnerServiceSMOImpl;

    @Autowired
    private IChainInoutOrderProductV1InnerServiceSMO chainInoutOrderProductV1InnerServiceSMOImpl;

    @Override
    public ResultVo validateChainOrder(StoreOrderDto storeOrderDto, List<StoreOrderCartDto> storeOrderCartDtos, ChainSupplierDto chainSupplierDto) throws MustParamsException, IOException, ApiRequestException {

        //获取订单收货地址
        StoreOrderAddressDto storeOrderAddressDto = new StoreOrderAddressDto();
        storeOrderAddressDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderAddressDto> userAddressDtos = storeOrderAddressInnerServiceSMOImpl.queryStoreOrderAddresss(storeOrderAddressDto);
        Assert.listOnlyOne(userAddressDtos, "未找到收货人信息");
        //获取收货地址，其中没有 省市区街道信息，再查一边
        StoreOrderAddressDto addressDto = userAddressDtos.get(0);
        AreaDto areaDto = new AreaDto();
        areaDto.setAreaCode(addressDto.getAreaCode());
        List<AreaDto> areaDtos = areaInnerServiceSMO.getWholeArea(areaDto);
        if (areaDtos.size() !=4){//查出来的省 市 区 街道 四个长度
            return new ResultVo(ResultVo.CODE_ERROR, "省市区街道信息不完整");
        }
        //获取api
        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式
        CheckOrderRequest checkOrderRequest = new CheckOrderRequest();
        CheckOrderRequest.Address address = new CheckOrderRequest.Address();
        address.setConsignee(addressDto.getUsername());
        address.setPhone(addressDto.getTel());

        address.setProvince(areaDtos.get(0).getAreaName());
        address.setCity(areaDtos.get(1).getAreaName());
        address.setArea(areaDtos.get(2).getAreaName());
        address.setStreet(areaDtos.get(3).getAreaName());

        address.setDescription(addressDto.getAddress());
        CheckOrderRequest.Spu spu = new CheckOrderRequest.Spu();
        List spuList = new ArrayList<>();
        for (StoreOrderCartDto storeOrderCartDto : storeOrderCartDtos){//校验供应链商品
                spu.setNumber(Long.parseLong(storeOrderCartDto.getCartNum()));//商品数量
                spu.setSku(Long.parseLong(storeOrderCartDto.getExtValueId()));//供应链id
                spuList.add(spu);
        }

        checkOrderRequest.setSpu(spuList);
        checkOrderRequest.setAddress(address);
        ApiResponse apiResponse = apiClient.exec(checkOrderRequest);
        //System.out.println(apiResponse.getMsg());
        List<CheckOrder> lists = apiResponse.getLists();
        CheckOrder checkOrder = lists.get(0);
        //System.out.println(checkOrder.getSkus().get(0));

        return new ResultVo(apiResponse.getCode() == 1 ? ResultVo.CODE_OK : ResultVo.CODE_ERROR, "供应链商品暂不可售。");
    }


    @Override
    public ResultVo notifyChainOrder(StoreOrderDto storeOrderDto, List<StoreOrderCartDto> storeOrderCartDtos, ChainSupplierDto chainSupplierDto) throws MustParamsException, IOException, ApiRequestException {
        System.out.println("--------------------------------异步下单下单下单--------------------------------------------");
        //获取订单收货地址
        StoreOrderAddressDto storeOrderAddressDto = new StoreOrderAddressDto();
        storeOrderAddressDto.setOrderId(storeOrderDto.getOrderId());
        List<StoreOrderAddressDto> userAddressDtos = storeOrderAddressInnerServiceSMOImpl.queryStoreOrderAddresss(storeOrderAddressDto);
        Assert.listOnlyOne(userAddressDtos, "未找到收货人信息");
        //获取收货地址，其中没有 省市区街道信息，再查一边
        StoreOrderAddressDto addressDto = userAddressDtos.get(0);
        AreaDto areaDto = new AreaDto();
        areaDto.setAreaCode(addressDto.getAreaCode());
        List<AreaDto> areaDtos = areaInnerServiceSMO.getWholeArea(areaDto);
        if (areaDtos.size() !=4){//查出来的省 市 区 街道 四个长度
            return new ResultVo(ResultVo.CODE_ERROR, "省市区街道信息不完整");
        }
        //获取api
        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式
        //下单
        PlayOrderRequest playOrderRequest = new PlayOrderRequest();
        PlayOrderRequest.Address address = new PlayOrderRequest.Address();
        address.setConsignee(addressDto.getUsername());
        address.setPhone(addressDto.getTel());

        address.setProvince(areaDtos.get(0).getAreaName());
        address.setCity(areaDtos.get(1).getAreaName());
        address.setArea(areaDtos.get(2).getAreaName());
        address.setStreet(areaDtos.get(3).getAreaName());
        address.setDescription(addressDto.getAddress());

        for (StoreOrderCartDto storeOrderCartDto : storeOrderCartDtos){
            if (storeOrderCartDto.getExtValueId() != null && storeOrderCartDto.getExtValueId().length() > 0){
                //String snOrderId = "SU"+GenerateCodeFactory.CODE_PREFIX_buyId;//供应链商品ID
                String snOrderId = "SU"+ GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_buyId);//供应链商品ID
                List spuList = new ArrayList<>();
                PlayOrderRequest.Spu spu3 = new PlayOrderRequest.Spu();
                //spu3.setNumber(Long.parseLong(storeOrderCartDto.getCartNum()));
                spu3.setNumber(Long.valueOf(Double.valueOf(storeOrderCartDto.getCartNum()).intValue()));
                spu3.setSku(Long.parseLong(storeOrderCartDto.getExtValueId()));
                spuList.add(spu3);
                playOrderRequest.setSpu(spuList);
                playOrderRequest.setAddress(address);
                playOrderRequest.setOrderSn(snOrderId);
                //playOrderRequest.setStrictMode(true);          //严格去重模式(有问题，暂时不知道怎么用)
                ApiResponse apiResponse = apiClient.exec(playOrderRequest);
                if(1 == apiResponse.getCode()){//下单成功，更新
                    StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
                    storeOrderCartPo.setCartId(storeOrderCartDto.getCartId());
                    storeOrderCartPo.setOrderId(storeOrderCartDto.getOrderId());
                    storeOrderCartPo.setOrderSn(snOrderId);
                    storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
                }else{
                    throw new IllegalArgumentException("供应链下单失败");
                }
            }}
        return new ResultVo(ResultVo.CODE_OK, "供应链商品下单成功。");
    }


    @Override
    public ResultVo queryProducts(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception {
        //获取api
        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式
        //商品列表
        int page = chainSupplierProductDto.getPage();
        int row = chainSupplierProductDto.getRow();
        int count = 0;
        int totalPages;//总页数
        List<ChainProductDto> chainProductDtos = new ArrayList<>();         
        if (!StringUtil.isEmpty(chainSupplierProductDto.getCatalogId())){   
            ChainSupplierCatalogDto chainSupplierCatalogDto = new ChainSupplierCatalogDto();
            chainSupplierCatalogDto.setCatalogId(chainSupplierProductDto.getCatalogId());
            List<ChainSupplierCatalogDto> queryChainSupplierCatalogs  = chainSupplierCatalogV1InnerServiceSMO.queryChainSupplierCatalogs(chainSupplierCatalogDto);
            GoodsGroupGoodsListRequest goodsGroupGoodsListRequest = new GoodsGroupGoodsListRequest();
            goodsGroupGoodsListRequest.setPage(page);
            goodsGroupGoodsListRequest.setLimit(row);
            if(queryChainSupplierCatalogs.size() > 0 ){//查询分类
                goodsGroupGoodsListRequest.setGroup_id(Integer.parseInt(queryChainSupplierCatalogs.get(0).getIntfUrlParam()));
            }
            ApiResponse<GoodsGroupGoodsList> apiResponse = apiClient.exec(goodsGroupGoodsListRequest);
            List<GoodsGroupGoodsList> listGoods = apiResponse.getLists();
            totalPages = apiResponse.getCount().intValue() / row;
            if (apiResponse.getCount().intValue() % row != 0){
                totalPages ++;
            }
            for (GoodsGroupGoodsList goods:listGoods){
                ChainProductDto productDto = new ChainProductDto();
                productDto.setProductId(goods.getId()+"");
                productDto.setCsId(chainSupplierDto.getCsId());
                checkProduct(productDto);
                productDto.setCoverPhoto(goods.getCover());
                productDto.setCatalogName(goods.getThird_category_name());
                productDto.setProdName(goods.getTitle());
                productDto.setUnitName(goods.getUnit());
                productDto.setState("2002");
                productDto.setCreateTime(new Date(goods.getCreated_time()));
                List<ChainProductValueDto> chainProductValueDtos = new ArrayList<>();
                ChainProductValueDto valueDto  = new ChainProductValueDto();
                valueDto.setProductId(goods.getId()+"");
                valueDto.setCsId(chainSupplierDto.getCsId());
                valueDto.setSpecName("默认规格");
                valueDto.setSpecValue("默认值");
                valueDto.setIsDefault("T");
                valueDto.setPrice(goods.getActivity_price()+"");
                chainProductValueDtos.add(valueDto);
                productDto.setChainProductValueDtos(chainProductValueDtos);
                chainProductDtos.add(productDto);
            }   
        }else {
            GoodsGroupGoodsListRequest goodsGroupGoodsListRequest = new GoodsGroupGoodsListRequest();
            goodsGroupGoodsListRequest.setPage(page);
            goodsGroupGoodsListRequest.setLimit(row);
            ApiResponse<GoodsGroupGoodsList> apiResponse = apiClient.exec(goodsGroupGoodsListRequest);
            List<GoodsGroupGoodsList> listGoods = apiResponse.getLists();
            totalPages = apiResponse.getCount().intValue() / row;
            if (apiResponse.getCount().intValue() % row != 0){
                totalPages ++;
            }
            for (GoodsGroupGoodsList goods:listGoods){
                ChainProductDto productDto = new ChainProductDto();
                productDto.setProductId(goods.getId()+"");
                productDto.setCsId(chainSupplierDto.getCsId());
                checkProduct(productDto);
                productDto.setCoverPhoto(goods.getCover());
                productDto.setCatalogName(goods.getThird_category_name());
                productDto.setProdName(goods.getTitle());
                productDto.setUnitName(goods.getUnit());
                productDto.setState("2002");
                productDto.setCreateTime(new Date(goods.getCreated_time()));
                List<ChainProductValueDto> chainProductValueDtos = new ArrayList<>();
                ChainProductValueDto valueDto  = new ChainProductValueDto();
                valueDto.setProductId(goods.getId()+"");
                valueDto.setCsId(chainSupplierDto.getCsId());
                valueDto.setSpecName("默认规格");
                valueDto.setSpecValue("默认值");
                valueDto.setIsDefault("T");
                valueDto.setPrice(goods.getActivity_price()+"");
                chainProductValueDtos.add(valueDto);
                productDto.setChainProductValueDtos(chainProductValueDtos);
                chainProductDtos.add(productDto);
            }
        }   
        ResultVo resultVo = new ResultVo( totalPages, count, chainProductDtos);
        return resultVo;
    }

    private void checkProduct(ChainProductDto product){
        ProductDto productDto = new ProductDto();
        productDto.setExtProdId(product.getProductId());
        productDto.setCsId(product.getCsId());
        int i = productInnerServiceSMOImpl.queryProductsCount(productDto);
        if (i > 0){
            product.setState("2002");
        }else{
            product.setState("1001");
        }
    }

    /**
     * <p>查询单个商品信息</p>
     *
     *
     * @param chainSupplierProductDto  订单调用链数据
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo querySingleProduct(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception{
        //获取api
        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式
        //商品详情(京东商品一个商品一个规格)
        ResultVo resultVo;
        if (!StringUtil.isEmpty(chainSupplierProductDto.getProductId())){
            GoodsDetailRequest goodsDetailRequest = new GoodsDetailRequest();
            goodsDetailRequest.setId(Long.valueOf(chainSupplierProductDto.getProductId()).longValue());
            ApiResponse<GoodsDetail> apiResponse = apiClient.exec(goodsDetailRequest);
            GoodsDetail goodsDetail = apiResponse.getObject();

            ChainProductDto productDto = new ChainProductDto();
            productDto.setProductId(goodsDetail.getId()+"");
            productDto.setCsId(chainSupplierDto.getCsId());
            productDto.setCoverPhoto(goodsDetail.getCover());
            productDto.setCatalogName(goodsDetail.getThird_category_name());
            productDto.setProdName(goodsDetail.getTitle());
            productDto.setUnitName(goodsDetail.getUnit());
            productDto.setState("2002");
            productDto.setCreateTime(new Date(goodsDetail.getCreated_time()));
            List<ChainProductValueDto> chainProductValueDtos = new ArrayList<>();
            ChainProductValueDto valueDto  = new ChainProductValueDto();
            valueDto.setProductId(goodsDetail.getId()+"");
            valueDto.setCsId(chainSupplierDto.getCsId());
            valueDto.setSpecName("默认规格");
            valueDto.setSpecValue("默认值");
            valueDto.setIsDefault("T");
            valueDto.setPrice(goodsDetail.getActivity_price()+"");
            valueDto.setValueId(goodsDetail.getSpecs().getOptions().get(0).getId()+"");//外部规格ID（）
            chainProductValueDtos.add(valueDto);
            productDto.setChainProductValueDtos(chainProductValueDtos);
            resultVo = new ResultVo( 0, 0, productDto);
        }else {
            resultVo = new ResultVo( 0, 0, null);
        }
        return resultVo;
    };


    /**
     * <p>获取评论信息</p>
     *
     *
     * @param chainSupplierProductDto  订单调用链数据
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo queryComments(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception{
        int page = chainSupplierProductDto.getPage();
        int row = chainSupplierProductDto.getRow();

        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式
        GoodsCommentsRequest goodsCommentsRequest = new GoodsCommentsRequest();
        goodsCommentsRequest.setPage(page);
        goodsCommentsRequest.setLimit(row);
        if (!StringUtil.isEmpty(chainSupplierProductDto.getProductId())){
            goodsCommentsRequest.setSku(Long.valueOf(chainSupplierProductDto.getProductId()).longValue());
        }else {
            goodsCommentsRequest.setSku((long)10362);//这个好像查询为空
        }
        ApiResponse<GoodsComments> apiResponse = apiClient.exec(goodsCommentsRequest);
        List<GoodsComments> list = apiResponse.getLists();

        int totalPages;//总页数
        totalPages = apiResponse.getCount().intValue() / row;
        if (apiResponse.getCount().intValue() % row != 0){
            totalPages ++;
        }
        ResultVo resultVo = new ResultVo( totalPages, apiResponse.getCount().intValue(), list);
        return resultVo;
    };


    /**
     * <p>查询物流信息</p>
     *
     *
     * @param chainSupplierProductDto  订单调用链数据
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo queryLogisticsInfo(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception{

        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式
        // 查询物流
        OrderLogisticRequest orderLogisticRequest = new OrderLogisticRequest();
        orderLogisticRequest.setOrderSn("SH20200622151638351628");
        orderLogisticRequest.setSku((long)9054);

        ApiResponse<OrderLogistic> apiResponse = apiClient.exec(orderLogisticRequest);
        OrderLogistic orderLogistic = apiResponse.getObject();
        System.out.println(orderLogistic.getInfo().getName());
        System.out.println(orderLogistic.getInfo().getNo());

        return null;
    };




    /**
     * <p>将供应链商品信息写入店铺信息</p>
     *
     *
     * @param chainSupplierProductDto
     * @return RoomDto 对象数据
     */
    @Override
    public ResultVo insertSingleProduct(ChainSupplierProductDto chainSupplierProductDto, ChainSupplierDto chainSupplierDto) throws Exception{

        String shopId = chainSupplierProductDto.getShopId();
        String storeId = chainSupplierProductDto.getStoreId();
        String groupId = chainSupplierProductDto.getGroupId();
        String ruleId = chainSupplierProductDto.getRuleId();

        ChainSupplierCatalogDto chainSupplierCatalogDto = new ChainSupplierCatalogDto();
        chainSupplierCatalogDto.setCatalogId(groupId);
        List<ChainSupplierCatalogDto> queryChainSupplierCatalogs  = chainSupplierCatalogV1InnerServiceSMO.queryChainSupplierCatalogs(chainSupplierCatalogDto);

        if(queryChainSupplierCatalogs.size() > 0 ){//查询分类
            groupId = queryChainSupplierCatalogs.get(0).getIntfUrlParam();
        }else{
            groupId = "";
        }

        ProductDto productDto = new ProductDto();
        productDto.setExtProdId(chainSupplierProductDto.getProductId());
        productDto.setCsId(chainSupplierProductDto.getCsId());

        int i = productInnerServiceSMOImpl.queryProductsCount(productDto);
        if (i > 0){
            return new ResultVo(ResultVo.CODE_ERROR, "已经存在该商品信息");
        }
        ApiClient apiClient = new ApiClient(chainSupplierDto.getAppId(), chainSupplierDto.getAppSecure());
        apiClient.setDebug(true); //设置调试模式

        //商品详情
        GoodsDetailRequest goodsDetailRequest = new GoodsDetailRequest();
        goodsDetailRequest.setId(Long.valueOf(chainSupplierProductDto.getProductId()).longValue());
        ApiResponse<GoodsDetail> apiResponse = apiClient.exec(goodsDetailRequest);
        GoodsDetail goodsDetail = apiResponse.getObject();

        //查询产品规格没有便插入
        ProductCategoryDto productCategoryDto = new ProductCategoryDto();
        productCategoryDto.setShopId(shopId);
        productCategoryDto.setCategoryId(groupId);
        //productCategoryDto.setCategoryName(groupApiList.get(0).getName()); //"聚合供应链");
        productCategoryDto.setStatusCd("0");
        List<ProductCategoryDto> productCategoryDtos = productCategoryInnerServiceSMOImpl.queryProductCategorys(productCategoryDto);
        productCategoryDto = new ProductCategoryDto();
        if (productCategoryDtos.size() > 0) {
            productCategoryDto = productCategoryDtos.get(0);
        } else {
            //选品分组列表
            GoodsGroupListRequest goodsGroupListRequest = new GoodsGroupListRequest();
            goodsGroupListRequest.setPage(1);
            goodsGroupListRequest.setLimit(50);
            ApiResponse<GoodsGroupList> apiResponseGL = apiClient.exec(goodsGroupListRequest);
            String finalGroupId = groupId;
            List<GoodsGroupList> groupApiList = apiResponseGL.getLists().stream().filter(gid->gid.getId() == Integer.parseInt(finalGroupId)).collect(Collectors.toList());

            ProductCategoryPo productCategoryPo = new ProductCategoryPo();
            productCategoryPo.setCategoryId(groupId);    //GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_categoryId));
            productCategoryPo.setCategoryName(groupApiList.get(0).getName().substring(0,4));  //"聚合供应链");
            productCategoryPo.setCateType("1");
            productCategoryPo.setCategoryLevel("1");
            productCategoryPo.setParentCategoryId("-1");
            productCategoryPo.setStoreId(storeId);
            productCategoryPo.setSeq("20");     //排序要找到一个合适的方法
            productCategoryPo.setIsShow("Y");
            productCategoryPo.setShopId(shopId);
            int flag = productCategoryInnerServiceSMOImpl.saveProductCategory(productCategoryPo);
            if (flag < 1) {
                return new ResultVo(ResultVo.CODE_ERROR, "供应链分组保存失败。");
            }

            productCategoryDto.setCategoryId(productCategoryPo.getCategoryId());
            productCategoryDto.setCategoryName(productCategoryPo.getCategoryName());
        }
        //商品仓库信息
        ShopHouseDto shopHouse = new ShopHouseDto();
        shopHouse.setShopId(shopId);
        shopHouse.setShName("供应链云仓");
        shopHouse.setStatusCd("0");
        List<ShopHouseDto> shopHouseList = shopHouseInnerServiceSMOImpl.queryShopHouses(shopHouse);
        shopHouse = new ShopHouseDto();
        if (shopHouseList.size() > 0) {
            shopHouse = shopHouseList.get(0);
        } else {
            ShopHousePo shopHousePo = new ShopHousePo();
            shopHousePo.setShId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_shId));
            shopHousePo.setShName("供应链云仓");
            shopHousePo.setShopId(shopId);
            shopHousePo.setShDesc("供应链云仓");
            shopHousePo.setShType("2807");//普通仓库
            int flag = shopHouseInnerServiceSMOImpl.saveShopHouse(shopHousePo);
            if (flag < 1) {
                return new ResultVo(ResultVo.CODE_ERROR, "供应链仓库保存失败。");
            }
            shopHouse.setShId(shopHousePo.getShId());
            shopHouse.setShName(shopHousePo.getShName());
        }
        //商品信息
        ProductPo productPo = new ProductPo();
        productPo.setProdName(goodsDetail.getTitle());
        productPo.setUnitName(goodsDetail.getUnit());
        productPo.setKeyword(goodsDetail.getThird_category_name());
        productPo.setProdDesc(goodsDetail.getTitle());  //getDescription());    //描述因为是图片改成Title
        productPo.setCategoryId(productCategoryDto.getCategoryId());
        productPo.setShId(shopHouse.getShId());
        productPo.setShName(shopHouse.getShName());
        productPo.setShopId(shopId);
        productPo.setStoreId(storeId);
        productPo.setProductId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_productId));     //;//改成供应链商品ID
        productPo.setBarCode(goodsDetail.getId()+"");       //这里须要修改为SPU_ID
        productPo.setIsPostage("2");
        productPo.setSort("8");
        productPo.setState("2002");
        productPo.setWarnStock("50");
        productPo.setExtProdId(goodsDetail.getId()+"");
        productPo.setCsId(chainSupplierDto.getCsId());
        productPo.setSuType(chainSupplierDto.getSuType());
        int flag = productInnerServiceSMOImpl.saveProduct(productPo);
        //关键词处理
        doSavakeywords(productPo);
        if (flag < 1) {
            return new ResultVo(ResultVo.CODE_ERROR, "关键词保存失败。");
        }
        //保存商品封面
        doSavaSupplyFile(goodsDetail.getCover(), productPo, FileRelDto.REL_TYPE_CD_GOODS_COVER);
        List<String> coversList = goodsDetail.getCovers();
        for (int carouselIndex = 0; carouselIndex < coversList.size(); carouselIndex++) {
            doSavaSupplyFile(coversList.get(carouselIndex), productPo, FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
        }
        //保存商品规格
        ProductSpecPo productSpecPo = new ProductSpecPo();
        productSpecPo.setSpecName(goodsDetail.getTitle().substring(0,5)+"规格");
        productSpecPo.setSpecId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_specId));
        productSpecPo.setShopId(shopId);
        productSpecPo.setStoreId(storeId);
        flag = productSpecInnerServiceSMOImpl.saveProductSpec(productSpecPo);
        if (flag < 1) {
            return new ResultVo(ResultVo.CODE_ERROR, goodsDetail.getTitle()+"规格保存失败");
        }
        ProductSpecDetailPo productSpecDetailPo = new ProductSpecDetailPo();
        productSpecDetailPo.setShopId(shopId);
        productSpecDetailPo.setStoreId(storeId);
        productSpecDetailPo.setDetailName("1");
        productSpecDetailPo.setDetailValue(goodsDetail.getUnit());
        productSpecDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
        productSpecDetailPo.setStoreId(productSpecPo.getStoreId());
        productSpecDetailPo.setSpecId(productSpecPo.getSpecId());
        flag = productSpecDetailInnerServiceSMOImpl.saveProductSpecDetail(productSpecDetailPo);
        if (flag < 1) {
            return new ResultVo(ResultVo.CODE_ERROR, goodsDetail.getTitle()+"保存规格值失败");
        }
        ProductSpecValuePo productSpecValuePo = new ProductSpecValuePo();
        productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId));
        productSpecValuePo.setSpecId(productSpecPo.getSpecId());
        productSpecValuePo.setProductId(productPo.getProductId());
        productSpecValuePo.setStock(goodsDetail.getStock().intValue()+"");
        productSpecValuePo.setSales(goodsDetail.getSale().intValue()+"");                       //销量

        productSpecValuePo.setIsDefault("T");
        productSpecValuePo.setShopId(shopId);
        productSpecValuePo.setBarCode(goodsDetail.getId()+"");
        productSpecValuePo.setWillExpire("0");
        productSpecValuePo.setAttrition("0");
        productSpecValuePo.setStoreId(storeId);
        productSpecValuePo.setExtValueId(goodsDetail.getSpecs().getOptions().get(0).getId().toString());
        if (!StringUtil.isEmpty(ruleId)){
            ProductPriceRuleDto productPriceRuleDto = new ProductPriceRuleDto();
            productPriceRuleDto.setRuleId(ruleId);
            List<ProductPriceRuleDto> productPriceRuleDtos = productPriceRuleV1InnerServiceSMOImpl.queryProductPriceRules(productPriceRuleDto);
            List<ProductSpecValueDto> productSpecValueDtos = new ArrayList<>();
            ProductSpecValueDto specValueDto = new ProductSpecValueDto();
            /*
                ├─ market_price	    number	是		市场价（单位：分）
                ├─ guide_price	    number	是		指导价（单位：分）
                ├─ activity_price	number	是		营销价（单位：分）
                ├─ sale_price	    number	是		销售价（单位：分）
                ├─ cost_price	    number	是		成本价（单位：分）
                ├─ 只有京东有营销价，所以没有营销价就用指导价代替
            */
            if(null == goodsDetail.getActivity_price()){
                goodsDetail.setActivity_price(goodsDetail.getGuide_price());
            }
            specValueDto.setPrice((goodsDetail.getSale_price().intValue()*0.01)+"");                //销售价（单位：分）
            specValueDto.setCostPrice((goodsDetail.getCost_price().intValue()*0.01)+"");            //成本价（单位：分）
            specValueDto.setVipPrice((goodsDetail.getActivity_price().intValue()*0.01)+"");         //营销价（单位：分）
            specValueDto.setOtPrice((goodsDetail.getMarket_price().intValue()*0.01)+"");            //市场价（单位：分）
            specValueDto.setOwnerPrice((goodsDetail.getActivity_price().intValue()*0.01)+"");       //业主价（单位：分）
            specValueDto.setDeduction((goodsDetail.getMarket_price().intValue()*0.01)+"");          //物业抵扣金（单位：分）
            
            productSpecValueDtos.add(specValueDto);
            productPriceRuleDtos.get(0).setProductSpecValueDtos(productSpecValueDtos);
            List<ProductSpecValueDto> tmpProductSpecValueDtos =  productPriceRuleV1InnerServiceSMOImpl.computeProductSpecValuePrices(productPriceRuleDtos.get(0));
            productSpecValuePo.setPrice(tmpProductSpecValueDtos.get(0).getPrice());                 //销售价（单位：分）
            productSpecValuePo.setCostPrice(tmpProductSpecValueDtos.get(0).getCostPrice());         //成本价（单位：分）
            productSpecValuePo.setVipPrice(tmpProductSpecValueDtos.get(0).getVipPrice());           //营销价（单位：分）
            productSpecValuePo.setOtPrice(tmpProductSpecValueDtos.get(0).getOtPrice());             //市场价（单位：分）
            productSpecValuePo.setDeduction(tmpProductSpecValueDtos.get(0).getDeduction());         //物业抵扣金（单位：分）
            productSpecValuePo.setOwnerPrice(tmpProductSpecValueDtos.get(0).getOwnerPrice());       //业主价（单位：分）
        }else {
            productSpecValuePo.setPrice((goodsDetail.getSale_price().intValue()*0.01)+"");          //销售价（单位：分）
            productSpecValuePo.setCostPrice((goodsDetail.getCost_price().intValue()*0.01)+"");      //成本价（单位：分）
            productSpecValuePo.setVipPrice((goodsDetail.getActivity_price().intValue()*0.01)+"");   //营销价（单位：分）
            productSpecValuePo.setOtPrice((goodsDetail.getMarket_price().intValue()*0.01)+"");      //市场价（单位：分）
            productCategoryDto.setOwnerPrice((goodsDetail.getActivity_price().intValue()*0.01)+""); //业主价（单位：分）
            productSpecValuePo.setDeduction((goodsDetail.getMarket_price().intValue()*0.01)+"");    //物业抵扣金（单位：分）
        }
        flag = productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存价格失败");
        }

        ProductDetailPo productDetailPo = new ProductDetailPo();
        productDetailPo.setShopId(shopId);
        productDetailPo.setStoreId(storeId);
        productDetailPo.setContent(goodsDetail.getDescription());
        productDetailPo.setProductId(productPo.getProductId());

        productDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));

        flag = productDetailInnerServiceSMOImpl.saveProductDetail(productDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存规格失败");
        }
        return new ResultVo(ResultVo.CODE_OK, "供应链商品保存成功。");
    }

    @Override
    public ResultVo callBackChainProduct(String param,ChainSupplierDto tmpChainSupplierDto) {


        JSONObject reqJson = JSONObject.parseObject(param);
        String type = reqJson.getString("type");
       JSONArray goodsId = reqJson.getJSONObject("data").getJSONArray("goodsIds");
        switch (type){
            case "goods.undercarriage":
                uderCarriage(goodsId); // 商品下架
                break;
            case "goods.on.sale":
                onSale(goodsId);
                break;
            case "goods.alter":
                alterGoods(goodsId,tmpChainSupplierDto);// 修改商品信息下架后从新采购入库
                break;
            case "goods.price.alter":
                alterGoods(goodsId,tmpChainSupplierDto);// 修改商品信息下架后从新采购入库
                break;
        }
        return new ResultVo(ResultVo.CODE_OK,ResultVo.MSG_OK);
    }

    private void alterGoods(JSONArray goodsId,ChainSupplierDto tmpChainSupplierDto) {
        String gId = "";
        for(int goodsIndex = 0 ;goodsIndex < goodsId.size(); goodsIndex++){
            gId = goodsId.getString(goodsIndex);

            // 检查商品是否上架
            ProductDto productDto = new ProductDto();
            productDto.setExtProdId(gId);
            productDto.setState(ProductDto.STATE_ON);
            List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
            if(productDtos == null || productDtos.size() == 0){
                continue;
            }

            ProductPo productPo = new ProductPo();
            productPo.setProductId(productDtos.get(0).getProductId());
            productPo.setState(ProductDto.STATE_OFF);
            productInnerServiceSMOImpl.updateProduct(productPo);

            ChainInoutOrderProductDto chainInoutOrderProductDto = new ChainInoutOrderProductDto();
            chainInoutOrderProductDto.setProductId(productDtos.get(0).getProductId());
            List<ChainInoutOrderProductDto> chainInoutOrderProductDtos = chainInoutOrderProductV1InnerServiceSMOImpl.queryChainInoutOrderProducts(chainInoutOrderProductDto);
            for (ChainInoutOrderProductDto product: chainInoutOrderProductDtos ){
                try {
                    ChainSupplierProductDto chainSupplierProductDto = new ChainSupplierProductDto();
                    chainSupplierProductDto.setShopId(product.getShopId());
                    chainSupplierProductDto.setStoreId(product.getStoreId());
                    chainSupplierProductDto.setGroupId(product.getGroupId());
                    chainSupplierProductDto.setRuleId(product.getRuleId());
                    chainSupplierProductDto.setProductId(product.getProductId());
                    chainSupplierProductDto.setCsId(product.getCsId());
                    insertSingleProduct(chainSupplierProductDto, tmpChainSupplierDto);
                }catch (Exception e) {
                    e.printStackTrace();
                    throw new IllegalArgumentException("供应链主动修改商品信息失败");
                }
            }
        }
    }


    /**
     * 上架
     * @param goodsId
     */
    private void onSale(JSONArray goodsId) {

        String gId = "";
        for(int goodsIndex = 0 ;goodsIndex < goodsId.size(); goodsIndex++){
            gId = goodsId.getString(goodsIndex);

            // 检查商品是否上架
            ProductDto productDto = new ProductDto();
            productDto.setExtProdId(gId);
            productDto.setState(ProductDto.STATE_ON);
            List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
            if(productDtos != null && productDtos.size()> 0){
                continue;
            }
             productDto = new ProductDto();
            productDto.setExtProdId(gId);
            productDto.setState(ProductDto.STATE_OFF);
          productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
            if(productDtos != null && productDtos.size()> 0){
                continue;
            }
            ProductPo productPo = new ProductPo();
            productPo.setProductId(productDtos.get(0).getProductId());
            productPo.setState(ProductDto.STATE_ON);
            productInnerServiceSMOImpl.updateProduct(productPo);
        }
    }

    private void uderCarriage(JSONArray goodsId) {
        String gId = "";
        for(int goodsIndex = 0 ;goodsIndex < goodsId.size(); goodsIndex++){
            gId = goodsId.getString(goodsIndex);

            // 检查商品是否上架
            ProductDto productDto = new ProductDto();
            productDto.setExtProdId(gId);
            productDto.setState(ProductDto.STATE_ON);
            List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
            if(productDtos == null || productDtos.size() == 0){
                continue;
            }

            ProductPo productPo = new ProductPo();
            productPo.setProductId(productDtos.get(0).getProductId());
            productPo.setState(ProductDto.STATE_OFF);
            productInnerServiceSMOImpl.updateProduct(productPo);
        }
    }


    ;

    /**
     * 保存关键词
     *
     * @param productPo
     */
    private void doSavakeywords(ProductPo productPo) {
        String[] keywor = productPo.getKeyword().replaceAll("；", ";").split(";");
        for (String keyword : keywor) {
            ProductServKeywordPo servKeywordPo = new ProductServKeywordPo();
            servKeywordPo.setKeywordId(GenerateCodeFactory.getGeneratorId("11"));
            servKeywordPo.setKeywordName(keyword.trim());
            servKeywordPo.setKeywordType(HousekeepingServDto.KEYWORD_PROD_TYPE_CD);
            servKeywordPo.setObjId(productPo.getProductId());
            servKeywordPo.setShopId(productPo.getShopId());
            int save = productServKeywordInnerServiceSMOImpl.saveProductServKeyword(servKeywordPo);
            if (save < 1) {
                throw new IllegalArgumentException("商品关键字保存失败");
            }
        }
    }


    private void doSavaSupplyFile(String url, ProductPo productPo, String fileTypeCd) throws Exception {
        FileDto fileDto = new FileDto();
        fileDto.setCommunityId("-1");
        fileDto.setContext(encodeImageToBase64(url));
        fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
        fileDto.setFileName(fileDto.getFileId());

        fileDto.setSuffix("jpeg");
        String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);

        FileRelPo fileRelPo = new FileRelPo();
        fileRelPo.setObjId(productPo.getProductId());
        fileRelPo.setRelTypeCd(fileTypeCd);
        fileRelPo.setFileRelId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_relId));
        fileRelPo.setFileRealName(fileName);
        fileRelPo.setFileSaveName(fileName);
        fileRelPo.setSaveWay(FileRelDto.SAVE_WAY_FTP);
        int save = fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);

        if (save < 1) {
            throw new IllegalArgumentException("保存供应链文件失败");
        }
    }

    //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
    private String encodeImageToBase64(String imgUrl) throws Exception {
        URL url = new URL(imgUrl);
        //打开链接
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
            conn.setRequestMethod("GET");
//超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
//得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
            byte[] buffer = new byte[1024];
//每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
//使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
//关闭输入流
            inStream.close();
            byte[] data = outStream.toByteArray();
//对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encode(data);
            return base64;//返回Base64编码过的字节数组字符串
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("图片转换失败,请联系客服!");
        }
    }

}
